package com.shd.edanpei.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.shd.edanpei.R;
import com.shd.edanpei.base.data.Preference;
import com.shd.edanpei.base.network.ApiConstant;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.exception.ResponeThrowable;
import com.shd.edanpei.base.network.model.NoDataResponse;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.bean.VersionBean;
import com.shd.edanpei.presenter.LoadingPresenter;
import com.shd.edanpei.ui.adapter.SplashImagesAdapter;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 启动页
 */
public class LoadingActivity extends Activity {

    private ImageView imageView;
    private ViewStub vsViewpager;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_load);
        imageView = findViewById(R.id.image);
        vsViewpager = findViewById(R.id.vs_splash_viewpager);

        //第一次启动APP
        //进入引导页

        //非第一次启动APP
        //进入闪屏页

    }

    @Override
    protected void onResume() {
        super.onResume();
        checkVersion();
    }

    /**
     * 检查是否需要更新
     */
    private void checkVersion() {
        ApiCreator.getApi().appVersion("android_plus")
                .compose(RxTransformer.<VersionBean>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<VersionBean>() {
                    @Override
                    protected void onSuccess(VersionBean data) {
//                        data.setAndroidIsUpdate(false);
                        try {
                            PackageInfo packageInfo = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
                            int versionCode = packageInfo.versionCode;
                            if (versionCode < data.getVersionNo()) {
                                if (data.isAndroidIsUpdate()) {
                                    //需强制更新
                                    toForcedUpadating();
                                } else {
                                    //非强制更新
//                                    toUpdate();
                                    getGuidePic();
                                }
                            } else {
//                                toSplashActivity();
                                getGuidePic();

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            getGuidePic();
                        }
                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                        toSplashActivity();
                    }
                });
    }

    private final String LOAD_VIEWPAGER = "load_viewpager";

    private void getGuidePic() {
        //是否启动过APP
        if (!Preference.getFlag(LOAD_VIEWPAGER)) {
            //未启动过引导页
            //1。加载引导页图片
            TypedArray typedArray = getResources().obtainTypedArray(R.array.splash_iamges);
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < typedArray.length(); i++) {
                list.add(typedArray.getResourceId(i, 0));
            }
            //2。设置引导页
            loadViewpager(list);
        } else {
            //已启动过引导页
            ApiCreator.getApi().getGuidePic()
                    .compose(RxTransformer.<String>errorHandle())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<String>() {
                        @Override
                        protected void onSuccess(String data) {
                            if (!TextUtils.isEmpty(data)) {
                                Glide.with(LoadingActivity.this).load(data).into(imageView);
                                CountDownTimer countDownTimer = new CountDownTimer(3 * 1000, 1000) {
                                    @Override
                                    public void onTick(long l) {

                                    }

                                    @Override
                                    public void onFinish() {
                                        toSplashActivity();
                                    }
                                };
                                countDownTimer.start();
                            } else {
                                toSplashActivity();
                            }
                        }

                        @Override
                        public void onFailure(ResponeThrowable throwable) {
                            super.onFailure(throwable);
                            toSplashActivity();
                        }
                    });
        }

    }

    private List<ImageView> imageViewList;


    public void loadViewpager(List<Integer> list) {
        imageView.setVisibility(View.GONE);
        vsViewpager.inflate();
        ViewPager viewPager = findViewById(R.id.vp_splash);
//        TextView tvSkip = findViewById(R.id.tv_loading_skip);
        final TextView button = findViewById(R.id.btn_splash_entry);
        imageViewList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(list.get(i));
            imageView.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
            imageViewList.add(imageView);
        }
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == imageViewList.size() - 1) {
                    //显示"进入应用"按钮
                    button.setAlpha(0);
                    button.setVisibility(View.VISIBLE);
                    button.animate().alpha(1).setDuration(500);
                } else {
                    //隐藏"进入应用"按钮
                    button.setVisibility(View.GONE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
//        tvSkip.setOnClickListener(this);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Preference.setFlag(LOAD_VIEWPAGER, true);
                toSplashActivity();
            }
        });
        viewPager.setAdapter(new SplashImagesAdapter(imageViewList));
    }


    private void toSplashActivity() {
        Intent intent = new Intent(this, SplashActivity.class);
        startActivity(intent);
        finish();
    }

    private void toUpdate() {
        AlertDialog builder = new AlertDialog.Builder(this)
                .setTitle("发现新版本")
                .setCancelable(false)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toSplashActivity();
                    }
                })
                .setPositiveButton("去更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toMarket(LoadingActivity.this, "com.shd.edanpei", null);
                    }
                }).show();
    }

    private void toForcedUpadating() {
        AlertDialog builder = new AlertDialog.Builder(this)
                .setTitle("发现新版本")
                .setCancelable(false)
                .setPositiveButton("去更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toMarket(LoadingActivity.this, "com.shd.edanpei", null);
                    }
                }).show();
    }


    /**
     * 跳转应用商店.
     *
     * @param context   {@link Context}
     * @param appPkg    包名
     * @param marketPkg 应用商店包名
     * @return {@code true} 跳转成功 <br> {@code false} 跳转失败
     */
    public static boolean toMarket(Context context, String appPkg, String marketPkg) {
        Uri uri = Uri.parse("market://details?id=" + appPkg);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (marketPkg != null) {// 如果没给市场的包名，则系统会弹出市场的列表让你进行选择。
            intent.setPackage(marketPkg);
        }
        try {
            context.startActivity(intent);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

}
